const { v4: uuidv4 } = require('uuid');

module.exports = {
  up: async (queryInterface) => {
    const now = new Date();

    // 1. 获取第一个租户
    const [tenants] = await queryInterface.sequelize.query(
      `SELECT id FROM tenants ORDER BY created_at ASC LIMIT 1`
    );

    if (tenants.length === 0) {
      console.log('No tenants found, skipping companies and departments seed');
      return;
    }

    const tenantId = tenants[0].id;

    // 2. 创建公司
    const company1Id = uuidv4();
    const company2Id = uuidv4();

    await queryInterface.bulkInsert('companies', [
      {
        id: company1Id,
        tenant_id: tenantId,
        name: '总公司',
        code: 'HQ',
        legal_name: '示例科技有限公司',
        tax_id: '91110000000000000X',
        contact_person: '张三',
        contact_phone: '010-12345678',
        contact_email: 'contact@example.com',
        address: '北京市朝阳区示例大厦',
        description: '集团总部',
        status: 'active',
        sort_order: 1,
        created_at: now,
        updated_at: now,
      },
      {
        id: company2Id,
        tenant_id: tenantId,
        name: '分公司',
        code: 'BRANCH',
        legal_name: '示例科技（上海）有限公司',
        tax_id: '91310000000000000Y',
        contact_person: '李四',
        contact_phone: '021-87654321',
        contact_email: 'shanghai@example.com',
        address: '上海市浦东新区示例路123号',
        description: '上海分公司',
        status: 'active',
        sort_order: 2,
        created_at: now,
        updated_at: now,
      },
    ]);

    // 3. 创建部门（总公司的部门）
    const techDeptId = uuidv4();
    const salesDeptId = uuidv4();
    const hrDeptId = uuidv4();
    const financeDeptId = uuidv4();
    
    // 技术部下的子部门
    const frontendDeptId = uuidv4();
    const backendDeptId = uuidv4();

    await queryInterface.bulkInsert('departments', [
      // 总公司一级部门
      {
        id: techDeptId,
        tenant_id: tenantId,
        company_id: company1Id,
        parent_id: null,
        name: '技术部',
        code: 'TECH',
        phone: '010-12345601',
        email: 'tech@example.com',
        description: '负责公司技术研发',
        level: 1,
        path: `/${techDeptId}`,
        status: 'active',
        sort_order: 1,
        created_at: now,
        updated_at: now,
      },
      {
        id: salesDeptId,
        tenant_id: tenantId,
        company_id: company1Id,
        parent_id: null,
        name: '销售部',
        code: 'SALES',
        phone: '010-12345602',
        email: 'sales@example.com',
        description: '负责产品销售',
        level: 1,
        path: `/${salesDeptId}`,
        status: 'active',
        sort_order: 2,
        created_at: now,
        updated_at: now,
      },
      {
        id: hrDeptId,
        tenant_id: tenantId,
        company_id: company1Id,
        parent_id: null,
        name: '人力资源部',
        code: 'HR',
        phone: '010-12345603',
        email: 'hr@example.com',
        description: '负责人力资源管理',
        level: 1,
        path: `/${hrDeptId}`,
        status: 'active',
        sort_order: 3,
        created_at: now,
        updated_at: now,
      },
      {
        id: financeDeptId,
        tenant_id: tenantId,
        company_id: company1Id,
        parent_id: null,
        name: '财务部',
        code: 'FINANCE',
        phone: '010-12345604',
        email: 'finance@example.com',
        description: '负责财务管理',
        level: 1,
        path: `/${financeDeptId}`,
        status: 'active',
        sort_order: 4,
        created_at: now,
        updated_at: now,
      },
      
      // 技术部的二级部门
      {
        id: frontendDeptId,
        tenant_id: tenantId,
        company_id: company1Id,
        parent_id: techDeptId,
        name: '前端开发组',
        code: 'FRONTEND',
        phone: '010-12345611',
        email: 'frontend@example.com',
        description: '负责前端开发',
        level: 2,
        path: `/${techDeptId}/${frontendDeptId}`,
        status: 'active',
        sort_order: 1,
        created_at: now,
        updated_at: now,
      },
      {
        id: backendDeptId,
        tenant_id: tenantId,
        company_id: company1Id,
        parent_id: techDeptId,
        name: '后端开发组',
        code: 'BACKEND',
        phone: '010-12345612',
        email: 'backend@example.com',
        description: '负责后端开发',
        level: 2,
        path: `/${techDeptId}/${backendDeptId}`,
        status: 'active',
        sort_order: 2,
        created_at: now,
        updated_at: now,
      },

      // 分公司部门
      {
        id: uuidv4(),
        tenant_id: tenantId,
        company_id: company2Id,
        parent_id: null,
        name: '业务部',
        code: 'BUSINESS',
        phone: '021-87654301',
        email: 'business@example.com',
        description: '分公司业务部',
        level: 1,
        path: `/${uuidv4()}`,
        status: 'active',
        sort_order: 1,
        created_at: now,
        updated_at: now,
      },
    ]);

    // 4. 更新超级管理员用户，分配到技术部
    const [users] = await queryInterface.sequelize.query(
      `SELECT id FROM users WHERE email = 'admin@saas.com' LIMIT 1`
    );

    if (users.length > 0) {
      await queryInterface.sequelize.query(
        `UPDATE users SET department_id = '${techDeptId}' WHERE id = '${users[0].id}'`
      );
    }

    console.log('✅ Companies and departments seeded successfully');
    console.log(`   - Created 2 companies`);
    console.log(`   - Created 7 departments (including nested departments)`);
    console.log(`   - Assigned admin user to 技术部`);
  },

  down: async (queryInterface) => {
    await queryInterface.bulkDelete('departments', null, {});
    await queryInterface.bulkDelete('companies', null, {});
    
    // 清除用户的部门关联
    await queryInterface.sequelize.query(
      `UPDATE users SET department_id = NULL WHERE department_id IS NOT NULL`
    );
  },
};

